import React, { useEffect, useState } from 'react';
import { bem } from "@/utils";
import classNames from 'classnames'
import { SkuInfo, OptionItemType } from "./typing";

export interface SkuSelectProps {
    skuSpecs: SkuInfo[],
    selectSku?: (object: any) => void
}

const SkuSelect: React.FC<SkuSelectProps> = (props) => {
    const {
        selectSku,
        skuSpecs,
        ...rest
    } = {
        ...props,
    }

    const b = bem('sku');

    const [skuSpecsList, setSkuSpecsList] = useState<SkuInfo[]>(skuSpecs);


    useEffect(() => {
        setSkuSpecsList(skuSpecs);
    }, [skuSpecs]);

    const changeSelectSku = (option: OptionItemType, optionIndex: number, skuAttr: SkuInfo, skuIndex: number) => {
        selectSku && selectSku({
            option,
            optionIndex,
            skuAttr,
            skuIndex
        });
    }

    return (
        <div className={b('select')}>
            {
                skuSpecsList?.map((item, index) => {
                    return (
                        <div className={b('select-list')} key={index}>
                            <div className={b('select-list-title')}>{item.attrName}</div>
                            <div className={b('select-list-sku')}>
                                {
                                    item.optionList?.map((optionItem, optionIndex) => {
                                        return (
                                            <span className={
                                                classNames(b('select-list-sku-item'), { active: optionItem.active })
                                            }
                                                key={optionItem.id}
                                                data-id={optionItem.id}
                                                onClick={() => { changeSelectSku(optionItem, optionIndex, item, index) }}
                                            >
                                                {optionItem.name}
                                            </span>
                                        )
                                    })
                                }
                            </div>
                        </div>
                    )
                })
            }
        </div>
    );
}

export default SkuSelect;